package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.AdminUserDao;
import com.leoman.dao.RecordInfoDao;
import com.leoman.entity.AdminUser;
import com.leoman.service.AdminUserService;
import com.leoman.utils.Md5Util;
import com.leoman.utils.RandomUtil;
import com.leoman.utils.SendSMSDemo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * AdminUserServiceImpl
 * Created by 涂奕恒 on 2016/10/20 0020 下午 5:01.
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserDao adminUserDao;

    @Autowired
    private RecordInfoDao recordInfoDao;

    @Override
    public List<AdminUser> findAll() {
        return adminUserDao.findAll();
    }

    @Override
    public Page<AdminUser> find(int pageNum, int pageSize) {
        return adminUserDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<AdminUser> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public AdminUser getById(int id) {
        return adminUserDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        adminUserDao.delete(id);
    }

    @Override
    public AdminUser create(AdminUser adminUser) {
        return adminUserDao.save(adminUser);
    }

    @Override
    public AdminUser update(AdminUser adminUser) {
        return adminUserDao.save(adminUser);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public AdminUser loginIn(HttpServletRequest request, String account, String password) {
        AdminUser adminUser = adminUserDao.findOneByAccount(account);

        if (null != adminUser && adminUser.getPassword().equals(password)) {
            // 修改最后登录时间
            adminUser.setLoginTime(System.currentTimeMillis());
            adminUserDao.save(adminUser);

            request.getSession().setAttribute(Constant.CURRENT_ADMIN_USER, adminUser);
            request.getSession().setAttribute(Constant.CURRENT_USER_TYPE, "admin");
            return adminUser;
        }

        return null;
    }

    @Override
    public void loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
    }

    @Override
    public Page<AdminUser> pageByParams(final String account, final String mobile, Integer pageNum, Integer pageSize) {
        return adminUserDao.findAll(new Specification<AdminUser>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<AdminUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotBlank(account)) {
                    Predicate pre = cb.like(root.get("account").as(String.class), "%" + account + "%");
                    predicateList.add(pre);
                }
                if (StringUtils.isNotBlank(mobile)) {
                    Predicate pre = cb.like(root.get("mobile").as(String.class), "%" + mobile + "%");
                    predicateList.add(pre);
                }
                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Integer saveAdminUser(Integer adminUserId, String account, String mobile, String password) {
        try {
            AdminUser adminUser;
            AdminUser accountAdminUser = adminUserDao.findOneByAccount(account);
            AdminUser mobileAdminUser = adminUserDao.findOneByMobile(mobile);

            if (null == adminUserId) {
                adminUser = new AdminUser();
                adminUser.setCreateTime(System.currentTimeMillis());
            } else {
                adminUser = adminUserDao.findOne(adminUserId);
            }

            if (null != accountAdminUser) {
                if (null == adminUser.getId() || !adminUser.getId().equals(accountAdminUser.getId())) {
                    return -1;
                }
            }

            if (null != mobileAdminUser) {
                if (null == adminUser.getId() || !adminUser.getId().equals(mobileAdminUser.getId())) {
                    return -2;
                }
            }

            adminUser.setAccount(account);
            adminUser.setMobile(mobile);
            adminUser.setPassword(password.length() > 20 ? password : Md5Util.md5(password));

            adminUserDao.save(adminUser);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer deleteAdminUser(HttpServletRequest request, Integer adminUserId) {
        Integer flag = 1;

        try {
            AdminUser sessionAdminUser = (AdminUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            adminUserDao.delete(adminUserId);

            if (sessionAdminUser.getId().equals(adminUserId)) {
                request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
                flag = 100;
            }

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer reSetAdminUserPassword(HttpServletRequest request, Integer adminUserId) {
        Integer flag = 1;

        try {
            AdminUser sessionAdminUser = (AdminUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            AdminUser adminUser = adminUserDao.findOne(adminUserId);

            if (StringUtils.isBlank(adminUser.getMobile())) {
                return -1;
            }

            if (sessionAdminUser.getId().equals(adminUserId)) {
                request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
                flag = 100;
            }

            String newPassword = RandomUtil.getCode();
            adminUser.setPassword(Md5Util.md5(newPassword));

            // 发送验证码
            SendSMSDemo.sendMessage(adminUser.getMobile(), newPassword);

            adminUserDao.save(adminUser);

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchDeleteAdminUser(HttpServletRequest request, Integer[] adminUserIds) {
        Integer flag = 1;

        try {
            AdminUser sessionAdminUser = (AdminUser) request.getSession().getAttribute(Constant.CURRENT_ADMIN_USER);

            for (Integer adminUserId : adminUserIds) {
                if (null == adminUserId) {
                    continue;
                }
                if (sessionAdminUser.getId().equals(adminUserId)) {
                    request.getSession().removeAttribute(Constant.CURRENT_ADMIN_USER);
                    flag = 100;
                }

                adminUserDao.delete(adminUserId);
            }

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}